package com.aia.prm.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.Assert;

import aia.cn.integration.nba.dto.premiumCalculation.PremiumCustomer;
import aia.cn.integration.nba.dto.premiumCalculation.PremiumPolicy;
import aia.cn.integration.nba.dto.premiumCalculation.PremiumPolicyRequest;
import aia.cn.integration.nba.dto.premiumCalculation.PremiumPolicyResponse;
import aia.cn.integration.nba.dto.premiumCalculation.PremiumRider;
import aia.cn.integration.nba.service.ArrayOf_tns11_nillable_PremiumCustomer;
import aia.cn.integration.nba.service.ArrayOf_tns11_nillable_PremiumRider;
import aia.cn.integration.nba.service.NBAServiceProxy;
import bsh.Interpreter;

import com.aia.aia4.web.json.Aia4Form1Json;
import com.aia.ilp.domain.SmsLog;
import com.aia.ilp.domain.SmsLogExample;
import com.aia.prm.config.AddressNotFoundException;
import com.aia.prm.config.ChinaAddress;
import com.aia.prm.config.CompanyCodes;
import com.aia.prm.domain.Card;
import com.aia.prm.domain.CardExample;
import com.aia.prm.domain.Coupon;
import com.aia.prm.domain.CouponExample;
import com.aia.prm.domain.Qnae;
import com.aia.prm.domain.QnaeExample;
import com.aia.prm.domain.Qnbe;
import com.aia.prm.domain.QnbeExample;
import com.aia.prm.domain.Qnce;
import com.aia.prm.domain.QnceExample;
import com.aia.prm.domain.Qnde;
import com.aia.prm.domain.QndeExample;
import com.aia.prm.domain.Qne;
import com.aia.prm.domain.QneExample;
import com.aia.prm.domain.Qnfe;
import com.aia.prm.domain.QnfeExample;
import com.aia.prm.domain.VOFile;
import com.aia.prm.domain.VOGroupExample;
import com.aia.prm.domain.VOLms;
import com.aia.prm.domain.VOLmsExample;
import com.aia.prm.domain.VOPext;
import com.aia.prm.domain.VOPextExample;
import com.aia.prm.domain.VOPextKey;
import com.aia.prm.domain.VOPlan;
import com.aia.prm.domain.VOPlanExample;
import com.aia.prm.web.ExtValue;
import com.aia.prm.web.Form1Action;
import com.aia.prm.web.Form2Action;
import com.aia.prm.web.IndexAction;
import com.aia.prm.web.ResultAction;
import com.aia.prm.web.h7n9.H7n9Form;
import com.aia.prm.web.json.PrmResultJson;
import com.aia.prm.web.json.PrmZanJson;
import com.aia.prm.web.qne.CorpAction;
import com.aia.prm.web.qne.CorpAxAction;
import com.aia.prm.web.qne.CorpAysAction;
import com.aia.prm.web.qne.CorpCouponAction;
import com.aia.prm.web.qne.CorpTypaAction;
import com.aia.prm.web.sanity.Testws1Action;
import com.aia.prm.web.sanity.Testws2Action;
import com.cfh.ahead.Constant;
import com.cfh.domain.User;
import com.cfh.domain.UserExample;
import com.cfh.domain.UserExample.Criteria;
import com.cfh.util.Tools;

@SuppressWarnings("rawtypes")
public class DefaultServiceImpl extends AbstractDefaultService implements DefaultService {
	private static final Logger logger = Logger.getLogger(DefaultServiceImpl.class);

	public User getUserByUsernameAndPassword(String username, String password) {
		if (logger.isDebugEnabled()) {
			logger.debug("getUserByUsernameAndPassword(String, String) - start"); //$NON-NLS-1$
		}

		Assert.hasText(username);
		Assert.hasText(password);
		UserExample ue = new UserExample();
		Criteria ct = ue.createCriteria();
		ct.andLOGIN_NAMEEqualTo(username);
		ct.andPASSWORDEqualTo(password);
		List list = getUserDAO().selectByExample(ue);
		if (list != null && list.size() > 0) {
			User returnUser = (User) list.get(0);
			if (logger.isDebugEnabled()) {
				logger.debug("getUserByUsernameAndPassword(String, String) - end"); //$NON-NLS-1$
			}
			return returnUser;
		} else {
			return null;
		}
	}

	public void changePassword(User currentUser, String newPassword) {
		currentUser.setPASSWORD(newPassword);
		getUserDAO().updateByPrimaryKey(currentUser);
	}

	public List selectConfig() {
		return configDAO.selectByExample(null);

	}

	public void executeTestws1(Testws1Action action) {

		if (!Tools.hasText(action.getScript())) {
			action.addActionError("Blank script!");
		}
		Interpreter inter = new Interpreter();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ByteArrayOutputStream os2 = new ByteArrayOutputStream();
		try {
			Logger newlogger = Logger.getLogger("com.aia.sanity.testws");
			PrintStream ps = new PrintStream(os);
			PrintStream ps2 = new PrintStream(os2);
			inter.setOut(ps);
			inter.setErr(ps2);
			inter.set("xml", action.getXml());
			inter.set("defaultService", this);
			inter.set("action", action);
			inter.set("newlogger", newlogger);
			inter.eval(action.getScript());
			Object o = inter.get("outString");
			action.setOutString(String.valueOf(o));
		} catch (Throwable e) {
			logger.warn(e);
			action.setOutString("Exception e:" + e);
			return;
		} finally {
			try {
				String out = os.toString("UTF-8");
				if (Tools.hasText(out)) {
					action.addActionMessage("Stdout:" + out);
				}

				String err = os2.toString("UTF-8");
				if (Tools.hasText(err)) {
					action.addActionError("Stderr:" + err);
				}
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}

	}

	public void executeTestws2(Testws2Action action) {

		if (!Tools.hasText(action.getScript())) {
			action.addActionError("Blank script!");
		}
		Interpreter inter = new Interpreter();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ByteArrayOutputStream os2 = new ByteArrayOutputStream();
		try {
			Logger newlogger = Logger.getLogger("com.aia.sanity.testws");
			PrintStream ps = new PrintStream(os);
			PrintStream ps2 = new PrintStream(os2);
			inter.setOut(ps);
			inter.setErr(ps2);
			inter.set("xml", action.getXml());
			inter.set("defaultService", this);
			inter.set("action", action);
			inter.set("newlogger", newlogger);
			inter.eval(action.getScript());
			Object o = inter.get("outString");
			action.setOutString(String.valueOf(o));
		} catch (Throwable e) {
			logger.warn(e);
			action.setOutString("EvalError e:" + e);
			return;
		} finally {
			try {
				String out = os.toString("UTF-8");
				if (Tools.hasText(out)) {
					action.addActionMessage("Stdout:" + out);
				}

				String err = os2.toString("UTF-8");
				if (Tools.hasText(err)) {
					action.addActionError("Stderr:" + err);
				}
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}

	}

	public void getAllPlan(IndexAction action) {

		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("重疾保障");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			action.setList1(list);
		}

		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("少儿教育");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			action.setList2(list);
		}

		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("养老年金");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			action.setList3(list);
		}
	}

	@SuppressWarnings("unchecked")
	public void getForm1(Form1Action action) {
		final String pid = action.getPid();

		VOPlan vOPlan = vOPlanDAO.selectByPrimaryKey(pid);
		if (vOPlan == null) {
			action.addActionError("找不到产品记录");
			return;
		}
		action.setvOplan(vOPlan);

		VOPextExample pextExample = new VOPextExample();
		pextExample.createCriteria().andPL_IDEqualTo(pid);
		pextExample.setOrderByClause("EX_ORDER");

		List<VOPext> list = vOPextDAO.selectByExample(pextExample);
		action.setListVOpext(list);

		List<VOPext> pactList = new ArrayList<VOPext>();
		List<VOPext> amountList = new ArrayList<VOPext>();
		List<VOPext> pictureList = new ArrayList<VOPext>();
		List<VOPext> pictureList2 = new ArrayList<VOPext>();

		for (VOPext item : list) {
			if ("合同".equals(item.getEX_TYPE())) {
				pactList.add(item);
			}
		}

		action.setPactList(pactList);
		for (VOPext item : list) {
			if ("字段".equals(item.getEX_TYPE())) {
				amountList.add(item);
			}
		}

		if (amountList.size() == 0) {
			action.addActionError("字段未定义");
			return;
		}

		action.setAmountList(amountList);

		int j = 0;
		for (VOPext item : list) {
			if ("展示图片".equals(item.getEX_TYPE())) {
				pictureList.add(item);
				j++;
				if (j >= 5) { // 展示图片，数量上限为5
					break;
				}
			}
		}

		int k = 0;
		for (VOPext item : list) {
			if ("手机版图片".equals(item.getEX_TYPE())) {
				pictureList2.add(item);
				k++;
				if (k >= 4) { // 手机版图片，数量上限为4
					break;
				}
			}
		}
		if (pictureList != null && pictureList.size() > 0) {
			action.setPictureList(pictureList);
		} else {
			action.setPictureList(null);
		}

		if (pictureList2 != null && pictureList2.size() > 0) {
			action.setPictureList2(pictureList2);
		} else {
			action.setPictureList2(null);
		}

		VOGroupExample gpExample = new VOGroupExample();
		gpExample.createCriteria().andPL_IDEqualTo(pid);

		List<String> ageList = new ArrayList<String>();
		for (int i = 0; i <= 70; i++) {
			ageList.add(String.valueOf(i));
		}
		action.setAgeList(ageList);
	}

	public void PrmForm1Json(Aia4Form1Json action) {
		final Qnae qnae = action.getQnae();
		if (qnae == null) {
			action.addActionError("数据为空");
			return;
		}
		final String pid = qnae.getQNXE_FROM();
		VOPlan plan = vOPlanDAO.selectByPrimaryKey(pid);
		if (plan == null) {
			action.addActionError("未找到该产品:" + pid);
			return;
		}

		VOPextExample pextExample = new VOPextExample();
		pextExample.createCriteria().andPL_IDEqualTo(pid);
		pextExample.setOrderByClause("EX_ORDER");
		List<VOPext> elist = vOPextDAO.selectByExample(pextExample);
		if (elist == null || elist.size() == 0) {
			action.addActionError("未找到该产品扩展信息定义:" + pid);
			return;
		}
		List<VOPext> amountList = new ArrayList<VOPext>();
		for (VOPext item : elist) {
			if ("字段".equals(item.getEX_TYPE())) {
				amountList.add(item);
			}
		}
		if (amountList == null || amountList.size() == 0) {
			action.addActionError("未找到该产品字段定义:" + pid);
			return;
		}
		boolean needValidateSMS = false;
		boolean needValidatePic = false;
		boolean agentCodeExist = false;
		for (VOPext item : amountList) {
			if (item != null && "手机验证码".equals(item.getEX_VALUE())) {
				needValidateSMS = true;
			}
			if (item != null && "图片验证码".equals(item.getEX_VALUE())) {
				needValidatePic = true;
			}
			if (item != null && "姓名".equals(item.getEX_VALUE()) && "Y".equals(item.getEX_FREEFLAG1())) {
				if (StringUtils.isBlank(qnae.getQNXE_NAME())) {
					action.addActionError("请输入姓名");
					return;
				}
			}
			if (item != null && "手机号码".equals(item.getEX_VALUE()) && "Y".equals(item.getEX_FREEFLAG1())) {
				if (StringUtils.isBlank(qnae.getQNXE_PHO())) {
					action.addActionError("请输入手机号码");
					return;
				}
			}
			if (item != null && "营销员编码".equals(item.getEX_VALUE()) && "Y".equals(item.getEX_FREEFLAG1())) {
				if (StringUtils.isBlank(qnae.getQNXE_CODE())) {
					action.addActionError("请输入营销员编码");
					return;
				} else {
					agentCodeExist = true;
				}
			}
		}

		try {
			if (needValidateSMS) {
				platValidateSMS(action, qnae);
			}
			if (needValidatePic) {
				platValidatePic(action, qnae.getQNXE_FREETEXT6());
			}
		} catch (ServiceException e) {
			action.addActionError(e.getMessage());
			return;
		}
		qnae.setQNXE_GUID(Tools.GUID());
		qnae.setQNXE_DATE(Tools.getToday());
		qnae.setQNXE_TIME(Tools.getTime());
		qnae.setQNXE_ADRESS(Tools.makeIPAddress());
		qnae.setQNXE_FREETEXT7(plan.getPL_NAME());
		qnaeDAO.insert(qnae);
		removeCaptcha();
		// 发短信
		String msgTemplate = plan.getPL_FREETEXT1();
		String dbTableName = plan.getPL_FREETEXT2();
		if (agentCodeExist && StringUtils.isNotEmpty(msgTemplate) && StringUtils.isNotEmpty(dbTableName)) {
			try {
				platSendSMS(plan, qnae, msgTemplate, dbTableName);
			} catch (Exception e) {
				logger.error("发送营销员短信出错:" + e, e);
			}
		}
	}

	private void platSendSMS(VOPlan plan, Qnae qnae, String msgTemplate, String dbTableName) throws ServiceException {
		String sql = "select AGI_PHONE from " + dbTableName + " where AGI_PROVINCECODE=? and AGI_CITYCODE=? and AGI_CODE=?";
		String provience = qnae.getQNXE_PROVINCE();
		String city = qnae.getQNXE_CITY();
		String agcode = qnae.getQNXE_CODE();
		if (StringUtils.isBlank(provience) || StringUtils.isBlank(city) || StringUtils.isBlank(agcode)) {
			return; // 没有参数
		}

		String msg = "友邦系统短信";
		String template = plan.getPL_FREETEXT1();
		if (StringUtils.isBlank(template)) {
			logger.warn("未定义手机短信模版");
			return; // 没有参数
		}
		msg = platBuildMessage(template, qnae, plan);

		String agentPhone = null;
		try {
			agentPhone = (String) jdbcTemplate.queryForObject(sql, new Object[] { provience, city, agcode }, String.class);
		} catch (Exception e) {
			logger.warn("在数据库表[" + dbTableName + "]中未找到营销员手机号:" + provience + "," + city + "," + agcode);
			return;
		}
		if (StringUtils.isEmpty(agentPhone)) {
			return;
		}

		sendSMS(msg, agentPhone, "aia4", false);
	}

	private String platBuildMessage(String template, Qnae qnae, VOPlan plan) {
		String result = template;
		//模板可用的占位符有:${省},${市},${区},${手机号码},${姓名},${性别},${年龄},${自由输入字段},${出生年},${出生月},${出生日},${来源},${产品名称},${电子邮件}
		result = result.replaceAll("\\$\\{省\\}", Tools.trimStr(qnae.getQNXE_PROVINCE()));
		result = result.replaceAll("\\$\\{市\\}", Tools.trimStr(qnae.getQNXE_CITY()));
		result = result.replaceAll("\\$\\{区\\}", Tools.trimStr(qnae.getQNXE_DISTRICT()));
		result = result.replaceAll("\\$\\{手机号码\\}", Tools.trimStr(qnae.getQNXE_PHO()));
		result = result.replaceAll("\\$\\{姓名\\}", Tools.trimStr(qnae.getQNXE_NAME()));
		result = result.replaceAll("\\$\\{性别\\}", Tools.trimStr(qnae.getQNXE_SEX()));
		result = result.replaceAll("\\$\\{年龄\\}", Tools.trimStr(qnae.getQNXE_BIRTH()));
		result = result.replaceAll("\\$\\{自由输入字段\\}", Tools.trimStr(qnae.getQNXE_BASE()));
		result = result.replaceAll("\\$\\{出生年\\}", Tools.trimStr(qnae.getQNXE_FREETEXT2()));
		result = result.replaceAll("\\$\\{出生月\\}", Tools.trimStr(qnae.getQNXE_FREETEXT3()));
		result = result.replaceAll("\\$\\{出生日\\}", Tools.trimStr(qnae.getQNXE_FREETEXT4()));
		result = result.replaceAll("\\$\\{来源\\}", Tools.trimStr(qnae.getQNXE_FROM()));
		result = result.replaceAll("\\$\\{产品名称\\}", Tools.trimStr(plan.getPL_NAME()));
		result = result.replaceAll("\\$\\{电子邮件\\}", Tools.trimStr(qnae.getQNXE_FREETEXT1()));
		return result;
	}

	private void platValidatePic(Aia4Form1Json action, String inputcode) throws ServiceException {
		HttpSession session = ServletActionContext.getRequest().getSession();
		if (session == null) {
			throw new ServiceException("会话失效");
		}
		String imgCode = (String) session.getAttribute(Constant.CAPTCHA_SESSION_HOLDER);
		if (StringUtils.isBlank(imgCode)) {
			throw new ServiceException("请再次获取图片验证码");
		}

		if (StringUtils.isBlank(inputcode)) {
			throw new ServiceException("请输入图片验证码");
		}
		if (!(inputcode.toLowerCase().equals(imgCode))) {
			throw new ServiceException("验证码输入错误");
		}
	}

	private void platValidateSMS(Aia4Form1Json action, final Qnae qnae) throws ServiceException {
		{// 校验手机验证码
			final String code = qnae.getQNXE_FREETEXT5();
			final String mobile = qnae.getQNXE_PHO();
			if (!Tools.hasText(code)) {
				throw new ServiceException("验证码为空");
			}

			if (!Tools.hasText(mobile)) {
				throw new ServiceException("手机号为空");
			}
			String powerKey = Tools.getProperties("sms.powerkey");
			if (code.equalsIgnoreCase(powerKey)) {
				logger.info("使用了超级验证码来验证");
				qnae.setQNXE_FREEFLAG1("Y");
			} else {
				qnae.setQNXE_FREEFLAG1("N");
				SmsLogExample example = new SmsLogExample();
				example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2NotEqualTo("Y");
				example.or(example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2IsNull());
				List list = smsLogDAO.selectByExample(example);
				if (list == null || list.size() == 0) {
					throw new ServiceException("手机验证码错误，可能是验证码过期，请尝试重新获取验证码");
				} else {// 如果发现验证码对了，那么将这个验证码即时做废，也就是让 SMSLOG_FREETEXT2=Y
					try {
						for (Iterator iterator = list.iterator(); iterator.hasNext();) {
							Object object = (Object) iterator.next();
							SmsLog item = (SmsLog) object;
							SmsLog toUpdate = new SmsLog();
							toUpdate.setSMSLOG_FREETEXT2("Y");
							toUpdate.setSMSLOG_GUID(item.getSMSLOG_GUID());
							smsLogDAO.updateByPrimaryKeySelective(toUpdate);
						}
					} catch (Exception e) {
						logger.warn("修改表smsLog出错", e);
					}
				}
			}
		}
	}

	public void getForm2(Form2Action action) {
		VOLms record = vOLmsDAO.selectByPrimaryKey(action.getRid());
		if (record == null) {
			action.addActionError("找不到记录");
			return;
		}
		action.setvOLms(record);

		final String pid = record.getPL_ID();

		VOPlan vOPlan = vOPlanDAO.selectByPrimaryKey(pid);
		if (vOPlan == null) {
			action.addActionError("找不到产品记录");
			return;
		}
		action.setvOplan(vOPlan);

		List<String> ageList = new ArrayList<String>();
		for (int i = 0; i <= 70; i++) {
			ageList.add(String.valueOf(i));
		}
		action.setAgeList(ageList);

	}

	private String smsContent(String argCode) {
		String s = "";
		if (argCode == null) {
			s = "";
		} else {
			s = argCode;
		}
		return "感谢您的参与，您的手机验证密码为" + s + "";
	}

	public void PrmSmsJson(com.aia.prm.web.json.PrmSmsJson action) {
		String verifyCode = "";
		String verifySms = "";
		{
			if (!Tools.hasText(action.getMobile())) {
				action.addActionError("手机号为空");
				return;
			}
		}
		{// 验证次数
			SmsLogExample example = new SmsLogExample();
			example.createCriteria().andSMSLOG_MOBILEEqualTo(action.getMobile());
			int count = 0;
			try {
				count = smsLogDAO.mm_countByExample(example);
			} catch (Exception e) {
				count = 0;
				logger.error(e);
			}
			if (count >= 5) {
				action.addActionError("给该手机号发短信的次数达到上限");
				return;
			}
		}
		// OK, 开始发短信
		{// 生成验证码
			verifyCode = Tools.randSixNumberString();
			verifySms = smsContent(verifyCode);
		}

		{// 插入SMSLOG表
			SmsLog smslog = new SmsLog();
			smslog.setSMSLOG_GUID(Tools.GUID());
			smslog.setSMSLOG_DATE(Tools.getToday());
			smslog.setSMSLOG_TIME(Tools.getTime());
			smslog.setSMSLOG_MOBILE(action.getMobile());
			smslog.setSMSLOG_FREETEXT1(verifyCode);
			smsLogDAO.insertSelective(smslog);

		}

		{// 发短信
			try {
				sendSMS(verifySms, action.getMobile(), "PRM_SMS", true);
			} catch (Exception e) {
				action.addActionError("出错了:" + e);
				return;
			}
			logger.debug("发送手机较验码：" + verifyCode);
		}

	}

	public void PrmForm2Json(com.aia.prm.web.json.PrmForm2Json action) {
		final VOLms lms = action.getLms();
		VOLms lookup = null;
		int mobileActCount = -1; // 手机激活的次数

		{// 校验手机验证码
			final String code = lms.getLMS_VARIFY_CODE();
			final String mobile = lms.getLMS_MOBILE();
			if (!Tools.hasText(code)) {
				action.addActionError("验证码为空");
				return;
			}

			if (!Tools.hasText(mobile)) {
				action.addActionError("手机号为空");
				return;
			}
			String powerKey = Tools.getProperties("sms.powerkey");
			if (code.equalsIgnoreCase(powerKey)) {
				logger.info("使用了超级验证码来验证");
				lms.setLMS_FREEFLAG2("Y");
			} else {
				lms.setLMS_FREEFLAG2("N");
				SmsLogExample example = new SmsLogExample();
				example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2NotEqualTo("Y");
				example.or(example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code).andSMSLOG_FREETEXT2IsNull());
				List list = smsLogDAO.selectByExample(example);
				if (list == null || list.size() == 0) {
					action.addActionError("验证码错误，可能是验证码过期，请尝试重新获取验证码");
					return;
				} else {// 如果发现验证码对了，那么将这个验证码即时做废，也就是让 SMSLOG_FREETEXT2=Y
					try {
						for (Iterator iterator = list.iterator(); iterator.hasNext();) {
							Object object = (Object) iterator.next();
							SmsLog item = (SmsLog) object;
							SmsLog toUpdate = new SmsLog();
							toUpdate.setSMSLOG_FREETEXT2("Y");
							toUpdate.setSMSLOG_GUID(item.getSMSLOG_GUID());
							smsLogDAO.updateByPrimaryKeySelective(toUpdate);
						}
					} catch (Exception e) {
						logger.warn("修改表smsLog出错", e);
					}

				}
			}
		}
		{// 校验是否已经手机激活LMS记录了
			lookup = vOLmsDAO.selectByPrimaryKey(lms.getLMS_GUID());
			if (lookup == null) {
				action.addActionError("不存在该记录，请检查页面参数，并返回主页");
				return;
			}
			if (Constant.Y.equalsIgnoreCase(lookup.getLMS_FLAG_VARIFY())) {
				action.addActionError("您已经提交过个人的信息了，不能重复提交");
				return;
			}
		}

		{// 一个手机号只能激活5次，也就是只能计算5次
			VOLmsExample example = new VOLmsExample();
			// 条件1：手机号；条件2：激活的
			example.createCriteria().andLMS_MOBILEEqualTo(lms.getLMS_MOBILE()).andLMS_FLAG_VARIFYEqualTo("Y");
			List allRecordsForThisMobile = vOLmsDAO.selectByExample(example);
			if (allRecordsForThisMobile == null || allRecordsForThisMobile.size() == 0) {
				mobileActCount = 0;
			} else {
				mobileActCount = allRecordsForThisMobile.size();
			}

			if (mobileActCount >= 6) {
				action.addActionError("该手机号的计算次数达到了上限");
				logger.debug("该手机号的计算次数达到了上限：" + lms.getLMS_MOBILE());
				return;
			}

		}
		{// 更新lookup到数据库
			lookup.setLMS_LX_PROVINCE(lms.getLMS_LX_PROVINCE());
			lookup.setLMS_LX_CITY(lms.getLMS_LX_CITY());
			lookup.setLMS_LX_DISTRICT(lms.getLMS_LX_DISTRICT());

			lookup.setLMS_LX_NAME(lms.getLMS_LX_NAME());
			lookup.setLMS_MOBILE(lms.getLMS_MOBILE());
			lookup.setLMS_LX_AGE(lms.getLMS_LX_AGE());
			lookup.setLMS_LX_SEX(lms.getLMS_LX_SEX());
			mobileActCount++;
			lookup.setLMS_MOBILE_COUNT((long) mobileActCount);
			lookup.setLMS_VARIFY_CODE(lms.getLMS_VARIFY_CODE());
			lookup.setLMS_VARIFY_DATETIME(Tools.getDateTime());
			lookup.setLMS_FLAG_VARIFY("Y");
		}

		{// 重要，发送NBA START =============================
			logger.debug("Before cacling the ammout, dumpObjectToXML:" + Tools.dumpObjectToXML(lookup));

			PremiumPolicyRequest soaReq = new PremiumPolicyRequest();
			PremiumPolicy policy = new PremiumPolicy();
			policy.setOrgId(makeOrgId(lookup));
			policy.setCurrencyCode("RMB");
			policy.setPayType("D");
			policy.setRiders(makeRiders(lookup));

			// 定义被保人 START
			PremiumCustomer customerBei = new PremiumCustomer();
			if (lookup.getLMS_BB_AGE() == null) {
				customerBei.setAge(20);
				logger.warn("Error! lookup.getLMS_BB_AGE()==null");
			} else {
				customerBei.setAge(lookup.getLMS_BB_AGE().intValue());
			}
			customerBei.setGender(lookup.getLMS_BB_SEX());
			customerBei.setOccupation("AA1");
			customerBei.setRelOfPrimeInsured("20");
			if ("子女投保".equals(lookup.getLMS_RELATION())) {
				customerBei.setOccupation("NA1");
			}
			// 定义被保人 END

			// 定义联系人，也就是投保人 START
			PremiumCustomer customerLian = new PremiumCustomer();
			customerLian.setOccupation("AA1");
			customerLian.setAge(lookup.getLMS_LX_AGE().intValue());
			customerLian.setGender(lookup.getLMS_LX_SEX());

			if ("子女投保".equals(lookup.getLMS_RELATION())) {
				customerLian.setRelOfPrimeInsured("25");
			} else if ("配偶投保".equals(lookup.getLMS_RELATION())) {
				customerLian.setRelOfPrimeInsured("21");
			} else if ("父母投保".equals(lookup.getLMS_RELATION())) {
				customerLian.setRelOfPrimeInsured("23");
			}
			// 定义联系人，也就是投保人 END

			// 设置所有的被保人信息 Start
			PremiumCustomer[] insuredArr = null;
			if ("本人投保".equals(lookup.getLMS_RELATION())) {
				insuredArr = new PremiumCustomer[] { customerBei };
			} else {
				insuredArr = new PremiumCustomer[] { customerBei, customerLian };
			}
			ArrayOf_tns11_nillable_PremiumCustomer arrayOfInsureds = new ArrayOf_tns11_nillable_PremiumCustomer();
			arrayOfInsureds.setPremiumCustomer(insuredArr);
			policy.setInsureds(arrayOfInsureds);
			// 设置所有的被保人信息 End

			// 设置投保人
			if ("本人投保".equals(lookup.getLMS_RELATION())) {
				policy.setOwner(customerBei);
			} else {
				policy.setOwner(customerLian);
			}

			soaReq.setPolicy(policy);
			logger.debug("****************  PRINT NBA REQUEST START  ****************");
			logger.debug(Tools.dumpObjectToXML(soaReq));
			logger.debug("****************  PRINT NBA REQUEST END    ****************");

			PremiumPolicyResponse response = null;
			if ("dev".equalsIgnoreCase(Tools.getProperties("website.evn"))) {
				action.addActionMessage("测试环境,跳过计算接口直接返回首期保费");
				lookup.setLMS_FISRT_AMOUT(BigDecimal.valueOf(12345.6d));
			} else {
				try {
					// 数据准备完毕，开始发消息
					NBAServiceProxy proxy = new NBAServiceProxy();
					logger.debug("01. init> Current Endpoint is:" + proxy.getEndpoint());
					String address_nba = Tools.getDatabaseProperty("service", "address_nba");
					if (Tools.hasText(address_nba)) {
						logger.debug("fetch config from db, address_nba=" + address_nba);
						proxy.setEndpoint(address_nba);
						logger.debug("02. after change> Current Endpoint is:" + proxy.getEndpoint());
					} else {
						logger.debug("fetch config from db, address_nba=<empty>");
					}
					// if
					// ("Y".equalsIgnoreCase(Tools.getProperties("webservice.isChanged")))
					// {
					// logger.debug("webservice.isChanged=Y, change address to:"
					// + Tools.getProperties("webservice.address"));
					// proxy.setEndpoint(Tools.getProperties("webservice.address"));
					// logger.debug("02. after change> Current Endpoint is:" +
					// proxy.getEndpoint());
					// }
					long beforeTime = System.currentTimeMillis();

					response = proxy.premiumPolicy(soaReq);
					long afterTime = System.currentTimeMillis();
					logger.debug("NBA成功返回！耗时:" + (afterTime - beforeTime) + "ms");
					logger.debug("%%%%%%%%%%%%%%%%  PRINT NBA RESPONSE START  %%%%%%%%%%%%%%%%");
					logger.debug(Tools.dumpObjectToXML(response));
					logger.debug("%%%%%%%%%%%%%%%%  PRINT NBA RESPONSE END    %%%%%%%%%%%%%%%%");
				} catch (Throwable e) {
					logger.error("连接NB异常：" + e, e);
					action.addActionError("服务暂不可用:[" + e + "],请联系网站管理员");
					return;
				}

				try {
					// 检查返回码
					Assert.notNull(response, "Response should not be null");
					Assert.notNull(response.getResult(), "Return should not be null");
					String flag = response.getResult().getReturnFlag();
					String msg = response.getResult().getErrorMessage();
					Assert.notNull(flag, "ReturnFlag should not be null");
					if (flag.equals("00")) {
						logger.debug("成功返回00代码!");
					} else {
						logger.error("连接NB成功，但是返回错误代码：" + flag + ",错误消息," + msg);
						action.addActionError("出错了,错误码:[" + flag + "],错误消息:[" + msg + "],请联系网站管理员");
						return;
					}

					// 将所有的首期保费相加
					PremiumPolicy backPolic = response.getPolicy();
					Assert.notNull(backPolic, "response.getPolicy() should not be null");
					ArrayOf_tns11_nillable_PremiumRider backNillableArrayRiders = backPolic.getRiders();
					Assert.notNull(backNillableArrayRiders, "response.getPolicy().getRiders() should not be null");
					PremiumRider[] arrayRiders = backNillableArrayRiders.getPremiumRider();
					Assert.notNull(arrayRiders, "backNillableArrayRiders.getPremiumRider() should not be null");
					Assert.isTrue(arrayRiders.length > 0, "arrayRiders should not be empty");
					float sumPremium = 0f;
					for (int i = 0; i < arrayRiders.length; i++) {
						Assert.notNull(arrayRiders[i], "arrayRiders[i] should not be null");
						float temp = arrayRiders[i].getModePremium();
						sumPremium += temp;
						logger.debug("将首期保费相加:第" + (i + 1) + "项保费=[" + temp + "元]");
					}
					logger.debug(" 将所有的首期保费相加后,总计保费=[" + sumPremium + "元]");
					lookup.setLMS_FISRT_AMOUT(BigDecimal.valueOf(sumPremium));

				} catch (Throwable e) {
					logger.error("连接NB成功返回，但是解析服务出错：" + e, e);
					action.addActionError("解析服务出错:[" + e + "],请联系网站管理员");
					return;
				}

			}
			// lookup.setLMS_FISRT_AMOUT(BigDecimal.valueOf(26789.12d));
			vOLmsDAO.updateByPrimaryKey(lookup);
			logger.debug("after cacling the ammout, dumpObjectToXML:" + Tools.dumpObjectToXML(lookup));
		}// 重要，发送NBA END =============================

		// sentLms(lookup, true);
		// 不自动发送，而是等待用户发送或是管理员手动发送
		{
			String code = "05";
			String msg = "计算成功，等待发送";
			lookup.setLMS_SEND_FLAG("N");
			lookup.setLMS_SEND_REF(code);
			lookup.setLMS_SEND_WHY(msg);
			lookup.setLMS_SEND_DATE(Tools.getToday());
			lookup.setLMS_SEND_TIME(Tools.getTime());
			vOLmsDAO.updateByPrimaryKey(lookup);
		}

		{// 试算成功后试算次数加1
			String pid = lookup.getPL_ID();
			VOPlan plan = vOPlanDAO.selectByPrimaryKey(pid);
			if (plan == null) {
				logger.error("找不到产品:" + pid);
				return;
			}

			Long count = plan.getPL_FREENUM2();
			if (count == null) {
				count = 0L;
			}
			count++;
			VOPlan newPlan = new VOPlan();
			newPlan.setPL_ID(pid);
			newPlan.setPL_FREENUM2(count);
			logger.debug(pid + "产品的试算次数增加到" + count);
			vOPlanDAO.updateByPrimaryKeySelective(newPlan);
		}
	}

	public String makeLmsTmplate(VOLms lookup) {
		String tmplate = "";
		try {
			tmplate = IOUtils.toString(this.getClass().getResourceAsStream("/lms.xml"), "UTF-8");
		} catch (IOException e) {
			logger.error("Cannot read classpath file: /lms.xml", e);
			throw new RuntimeException(e);
		}
		String campaign = Tools.getDatabaseProperty("service", "campaign");
		try {
			boolean isDMType = false;
			VOPlan plan = vOPlanDAO.selectByPrimaryKey(lookup.getPL_ID());
			if (plan != null && "DM渠道".equals(plan.getPL_TYPE())) {
				isDMType = true;
			}

			if (isDMType) {
				String dmcode = Tools.getDatabaseProperty("service", "dm_campaign");
				if (StringUtils.isNotBlank(dmcode)) {
					campaign = dmcode;
				}
			}
		} catch (Exception e) {
			logger.error("Encouter error when fetch dm_campaign:" + e, e);
		}
		final String agent = Tools.getDatabaseProperty("service", "agent");

		tmplate = tmplate.replaceAll("\\$\\{campaign\\}", Tools.trimStr(campaign));
		tmplate = tmplate.replaceAll("\\$\\{Agent\\}", Tools.trimStr(agent));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_SEX\\}", Tools.trimStr(lookup.getLMS_BB_SEX()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_MOBILE\\}", Tools.trimStr(lookup.getLMS_MOBILE()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_CITY\\}", Tools.trimStr(lookup.getLMS_BB_CITY()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_PROVINCE\\}", Tools.trimStr(lookup.getLMS_BB_PROVINCE()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_DISTRICT\\}", Tools.trimStr(lookup.getLMS_BB_DISTRICT()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_SEX\\}", Tools.trimStr(lookup.getLMS_BB_SEX()));
		String name = lookup.getLMS_LX_NAME();
		String firstname = "";
		String lastname = "";
		if (Tools.hasText(name)) {
			lastname = name.substring(0, 1);
			if (name.length() >= 2) {
				firstname = name.substring(1);
			}
		}
		tmplate = tmplate.replaceAll("\\$\\{firstname\\}", firstname);
		tmplate = tmplate.replaceAll("\\$\\{lastname\\}", lastname);

		String birthyear = "";
		try {
			if (lookup.getLMS_LX_AGE() != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
				String tempThisYearStr = sdf.format(new java.util.Date());
				Integer tempThisYearInt = Integer.valueOf(tempThisYearStr);
				int intTemp = tempThisYearInt - lookup.getLMS_LX_AGE().intValue();
				birthyear = String.valueOf(intTemp);
			}
		} catch (Exception e) {
			logger.warn("birthyear!", e);
			birthyear = "";
		}

		tmplate = tmplate.replaceAll("\\$\\{Birthyear\\}", birthyear);
		String marriage = "";
		if ("配偶投保".equals(lookup.getLMS_RELATION())) {
			marriage = "YH";
		}
		tmplate = tmplate.replaceAll("\\$\\{Marriage\\}", marriage);

		String childrenGender = "";
		String childBirthyear = "";
		if ("子女投保".equals(lookup.getLMS_RELATION())) {
			childrenGender = lookup.getLMS_BB_SEX();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			String tempThisYearStr = sdf.format(new java.util.Date());
			Integer tempThisYearInt = Integer.valueOf(tempThisYearStr);
			int intTemp = tempThisYearInt - lookup.getLMS_BB_AGE().intValue();
			childBirthyear = String.valueOf(intTemp);
		}
		tmplate = tmplate.replaceAll("\\$\\{ChildrenGender\\}", childrenGender);
		tmplate = tmplate.replaceAll("\\$\\{ChildBirthyear\\}", childBirthyear);

		// 发送至LMS的机会
		// 保费计算日期+空格+"在官网试算"+主险短名+空格+"保额"+基本保险金+空格+被保险人关系+被保险人年龄+“首期保费"+首期保费

		String description1 = "";
		String baoxianAmout = "";
		String bbSex = "男";

		{// 得到保险金显示名
			// try {
			// VOPextKey key = new VOPextKey();
			// key.setEX_TYPE("保险金");
			// key.setPL_ID(lookup.getPL_ID());
			// try {
			// key.setEX_VALUE(String.valueOf(lookup.getLMS_INSU_AMOUT().intValue()));
			// } catch (Exception e) {
			// logger.warn("数字转化出错", e);
			// }
			//
			// VOPext vOpext = vOPextDAO.selectByPrimaryKey(key);
			// if (vOpext == null) {
			// logger.warn("查找保险金出错, 找不到记录");
			// }
			// baoxianAmout = vOpext.getEX_NAME();
			//
			// } catch (Exception e) {
			// logger.warn("查找保险金出错", e);
			// if (!Tools.hasText(baoxianAmout)) {
			// try {
			// baoxianAmout = lookup.getLMS_INSU_AMOUT().toString();
			// } catch (Exception e2) {
			// logger.warn("UN-KNOWN", e);
			// }
			// }
			// }

			try {
				baoxianAmout = String.valueOf(lookup.getLMS_INSU_AMOUT().intValue());
			} catch (Exception e2) {
				logger.warn("UN-KNOWN", e2);
			}

		}
		if ("F".equalsIgnoreCase(lookup.getLMS_BB_SEX())) {
			bbSex = "女";
		} else {
			bbSex = "男";
		}
		String baoFei = "";
		if (lookup.getLMS_FISRT_AMOUT() != null) {
			baoFei = String.valueOf(lookup.getLMS_FISRT_AMOUT().intValue());
		}

		String tempTodayStr = lookup.getLMS_DATE();
		try {
			SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd");
			Date date = formatter2.parse(tempTodayStr);
			tempTodayStr = formatter.format(date);
		} catch (Exception e) {
			logger.error("Format Date error:" + tempTodayStr);
		}

		String cityName = "";
		{
			cityName = lookup.getLMS_LX_DISTRICT();
		}

		description1 = tempTodayStr + " " + cityName + "用户 试算" + lookup.getGP_NAME() + " 保额" + baoxianAmout + " "
				+ lookup.getLMS_RELATION() + " 被保人 " + lookup.getLMS_BB_AGE() + "岁" + bbSex + " 首期保费" + baoFei;
		tmplate = tmplate.replaceAll("\\$\\{Description1\\}", description1);
		String companyCode = "";
		companyCode = CompanyCodes.pickCompanyCode(lookup.getLMS_BB_PROVINCE(), lookup.getLMS_BB_CITY(), lookup.getLMS_BB_DISTRICT());
		tmplate = tmplate.replaceAll("\\$\\{companyCode\\}", companyCode);

		return tmplate;
	}

	public String makeAxLmsTmplate(Qnbe lookup) {
		String tmplate = "";
		try {
			tmplate = IOUtils.toString(this.getClass().getResourceAsStream("/lms_ax.xml"), "UTF-8");
		} catch (IOException e) {
			logger.error("Cannot read classpath file: /lms_ax.xml", e);
			throw new RuntimeException(e);
		}
		final String campaign = Tools.getDatabaseProperty("service", "ax_campaign");
		final String agent = Tools.getDatabaseProperty("service", "ax_agent" + lookup.getQNXE_CODE());

		tmplate = tmplate.replaceAll("\\$\\{campaign\\}", Tools.trimStr(campaign));
		tmplate = tmplate.replaceAll("\\$\\{Agent\\}", Tools.trimStr(agent));
		String sex = "M";
		if ("女".equals(lookup.getQNXE_SEX())) {
			sex = "F";
		}
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_SEX\\}", sex);
		tmplate = tmplate.replaceAll("\\$\\{LMS_MOBILE\\}", Tools.trimStr(lookup.getQNXE_PHO()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_CITY\\}", "SH");
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_PROVINCE\\}", "SH");
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_DISTRICT\\}", "");
		String name = lookup.getQNXE_NAME();
		String firstname = "";
		String lastname = "";
		if (Tools.hasText(name)) {
			lastname = name.substring(0, 1);
			if (name.length() >= 2) {
				firstname = name.substring(1);
			}
		}
		tmplate = tmplate.replaceAll("\\$\\{firstname\\}", firstname);
		tmplate = tmplate.replaceAll("\\$\\{lastname\\}", lastname);

		String birthyear = "";
		try {
			if (lookup.getQNXE_BIRTH() != null && lookup.getQNXE_BIRTH().length() >= 4) {
				birthyear = lookup.getQNXE_BIRTH().substring(0, 4);
			}
		} catch (Exception e) {
			logger.warn("birthyear!", e);
			birthyear = "";
		}

		tmplate = tmplate.replaceAll("\\$\\{Birthyear\\}", birthyear);
		tmplate = tmplate.replaceAll("\\$\\{Marriage\\}", "");

		// 发送至LMS的机会
		// 需要默认为“安欣生活终端机中选定营销员”+ <birthyear>+“出生”+选择的保险需求(3.b)

		String description1 = "安欣生活终端机中选定营销员" + lookup.getQNXE_AGENTTYPE() + " " + birthyear + "出生 选择的保险需求" + lookup.getQNXE_BASE();
		tmplate = tmplate.replaceAll("\\$\\{Description1\\}", description1);
		String companyCode = "0986";
		tmplate = tmplate.replaceAll("\\$\\{companyCode\\}", companyCode);
		return tmplate;
	}

	public String makeAysLmsTmplate(Qnde lookup) {
		String tmplate = "";
		try {
			tmplate = IOUtils.toString(this.getClass().getResourceAsStream("/lms_ax.xml"), "UTF-8");
		} catch (IOException e) {
			logger.error("Cannot read classpath file: /lms_ax.xml", e);
			throw new RuntimeException(e);
		}
		final String campaign = Tools.getDatabaseProperty("service", "ays_campaign");
		final String agent = Tools.getDatabaseProperty("service", "ax_agent" + lookup.getQNXE_CODE());

		tmplate = tmplate.replaceAll("\\$\\{campaign\\}", Tools.trimStr(campaign));
		tmplate = tmplate.replaceAll("\\$\\{Agent\\}", Tools.trimStr(agent));
		String sex = "M";
		if ("女".equals(lookup.getQNXE_SEX())) {
			sex = "F";
		}
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_SEX\\}", sex);
		tmplate = tmplate.replaceAll("\\$\\{LMS_MOBILE\\}", Tools.trimStr(lookup.getQNXE_PHO()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_CITY\\}", "SH");
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_PROVINCE\\}", "SH");
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_DISTRICT\\}", "");
		String name = lookup.getQNXE_NAME();
		String firstname = "";
		String lastname = "";
		if (Tools.hasText(name)) {
			lastname = name.substring(0, 1);
			if (name.length() >= 2) {
				firstname = name.substring(1);
			}
		}
		tmplate = tmplate.replaceAll("\\$\\{firstname\\}", firstname);
		tmplate = tmplate.replaceAll("\\$\\{lastname\\}", lastname);

		String birthyear = "";
		try {
			if (lookup.getQNXE_BIRTH() != null && lookup.getQNXE_BIRTH().length() >= 4) {
				birthyear = lookup.getQNXE_BIRTH().substring(0, 4);
			}
		} catch (Exception e) {
			logger.warn("birthyear!", e);
			birthyear = "";
		}

		tmplate = tmplate.replaceAll("\\$\\{Birthyear\\}", birthyear);
		tmplate = tmplate.replaceAll("\\$\\{Marriage\\}", "");

		// 发送至LMS的机会
		// 需要默认为“安欣生活终端机中选定营销员”+ <birthyear>+“出生”+选择的保险需求(3.b)

		String description1 = "爱婴室活动网站选定营销员" + lookup.getQNXE_AGENTTYPE() + " " + birthyear + "出生 选择的保险需求" + lookup.getQNXE_BASE();
		tmplate = tmplate.replaceAll("\\$\\{Description1\\}", description1);
		String companyCode = "0986";
		tmplate = tmplate.replaceAll("\\$\\{companyCode\\}", companyCode);
		return tmplate;
	}

	public String makeTypaLmsTmplate(Qnae lookup) {
		String tmplate = "";
		try {
			tmplate = IOUtils.toString(this.getClass().getResourceAsStream("/lms_typa.xml"), "UTF-8");
		} catch (IOException e) {
			logger.error("Cannot read classpath file: /lms_typa.xml", e);
			throw new RuntimeException(e);
		}
		final String campaign = Tools.getDatabaseProperty("service", "platform_campaign");
		final String agent = Tools.getDatabaseProperty("service", "platform_agent");

		tmplate = tmplate.replaceAll("\\$\\{campaign\\}", Tools.trimStr(campaign));
		tmplate = tmplate.replaceAll("\\$\\{Agent\\}", Tools.trimStr(agent));
		String sex = "M";
		if ("女".equals(lookup.getQNXE_SEX())) {
			sex = "F";
		}
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_SEX\\}", sex);
		tmplate = tmplate.replaceAll("\\$\\{LMS_MOBILE\\}", Tools.trimStr(lookup.getQNXE_PHO()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_CITY\\}", Tools.trimStr(lookup.getQNXE_CITY()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_PROVINCE\\}", Tools.trimStr(lookup.getQNXE_PROVINCE()));
		tmplate = tmplate.replaceAll("\\$\\{LMS_BB_DISTRICT\\}", Tools.trimStr(lookup.getQNXE_DISTRICT())); // 不发送值，待定
		String name = lookup.getQNXE_NAME();
		String firstname = "";
		String lastname = "";
		if (Tools.hasText(name)) {
			lastname = name.substring(0, 1);
			if (name.length() >= 2) {
				firstname = name.substring(1);
			}
		}
		tmplate = tmplate.replaceAll("\\$\\{firstname\\}", Tools.trimStr(firstname));
		tmplate = tmplate.replaceAll("\\$\\{lastname\\}", Tools.trimStr(lastname));

		String birthyear = "";
		try {
			if (lookup.getQNXE_FREETEXT2() != null && lookup.getQNXE_FREETEXT2().length() >= 4) {
				birthyear = lookup.getQNXE_FREETEXT2().substring(0, 4);
			}
		} catch (Exception e) {
			logger.warn("birthyear!", e);
			birthyear = "";
		}

		tmplate = tmplate.replaceAll("\\$\\{Birthyear\\}", Tools.trimStr(birthyear));
		tmplate = tmplate.replaceAll("\\$\\{Marriage\\}", "");

		String tempTodayStr = "";
		{
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd");
			tempTodayStr = formatter.format(new Date());
		}

		// 发送至LMS的机会
		String description1 = tempTodayStr + "信息收集平台,姓名:" + lookup.getQNXE_NAME() + ",性别:" + lookup.getQNXE_SEX() + ",年龄:"
				+ lookup.getQNXE_BIRTH() + ",手机:" + lookup.getQNXE_PHO()+ ",产品:" + lookup.getQNXE_FROM()+ lookup.getQNXE_FREETEXT7();
		tmplate = tmplate.replaceAll("\\$\\{Description1\\}", Tools.trimStr(description1));
		String companyCode = "0986";
		try {
			companyCode = CompanyCodes.pickCompanyCode(lookup.getQNXE_PROVINCE(), lookup.getQNXE_CITY(), lookup.getQNXE_DISTRICT());
		} catch (Exception e) {
			companyCode = "0986";
		}
		tmplate = tmplate.replaceAll("\\$\\{companyCode\\}", Tools.trimStr(companyCode));
		return tmplate;
	}

	private ArrayOf_tns11_nillable_PremiumRider makeRiders(VOLms lookup) {
		final List<PremiumRider> list = new ArrayList<PremiumRider>();

		{
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("01");
			// PlanCode 处理 因为NB系统的PlanCode是右对齐的，所以需要填“”补缺
			// 主险代码
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_MAINCODE(), 10));
			list.add(rider1);
		}

		if (Tools.hasText(lookup.getGP_EXTCODE1())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("02");
			// 附加代码1
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE1(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE2())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("03");
			// 附加代码2
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE2(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE3())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("04");
			// 附加代码3
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE3(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE3())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("05");
			// 附加代码4
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE4(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE3())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("06");
			// 附加代码5
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE5(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE3())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("07");
			// 附加代码6
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE6(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE3())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("08");
			// 附加代码7
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE7(), 10));
			list.add(rider1);
		}
		if (Tools.hasText(lookup.getGP_EXTCODE3())) {
			PremiumRider rider1 = makePrototypeRider(lookup);
			rider1.setRidNum("09");
			// 附加代码8
			rider1.setPlanCode(StringUtils.leftPad(lookup.getGP_EXTCODE8(), 10));
			list.add(rider1);
		}

		PremiumRider[] riders = list.toArray(new PremiumRider[list.size()]);

		ArrayOf_tns11_nillable_PremiumRider arrayOfRider = new ArrayOf_tns11_nillable_PremiumRider();
		arrayOfRider.setPremiumRider(riders);
		return arrayOfRider;
	}

	/**
	 * 创建通用PremiumRider
	 * 
	 * @param lookup
	 * @return
	 */
	private PremiumRider makePrototypeRider(VOLms lookup) {
		// 保额
		PremiumRider rider1 = new PremiumRider();
		rider1.setCoverage(lookup.getLMS_INSU_AMOUT().floatValue());
		char c = 'M';
		try {
			c = lookup.getLMS_BB_SEX().charAt(0);
		} catch (Exception e) {
			logger.warn("Err when makePrototypeRider:" + e);
			c = 'M';
		}
		// 被保人性别char(1)F/M
		rider1.setSex(c);
		// 被保人年龄
		rider1.setIssueAge(lookup.getLMS_BB_AGE().intValue());
		rider1.setIssueDate(Tools.getToday());
		// 被保人职业代码
		String relation = lookup.getLMS_RELATION();
		if ("子女投保".equals(relation)) {
			rider1.setOccupation("NA1");
		} else {
			rider1.setOccupation("AA1");
		}
		// 缴费方式
		rider1.setPayMode('A');
		// 购买份数
		rider1.setUnit(1);
		return rider1;
	}

	static String defaultOrgId = "N00001";

	private String makeOrgId(VOLms lookup) {
		String result = "";
		final String province = lookup.getLMS_BB_PROVINCE();
		final String city = lookup.getLMS_BB_CITY();
		if ("SH".equalsIgnoreCase(province)) {
			result = "N00001";
		}
		if ("BJ".equalsIgnoreCase(province)) {
			result = "N00002";
		}
		if ("JS".equalsIgnoreCase(province)) {
			result = "N00003";
		}
		if ("GD".equalsIgnoreCase(province)) {
			result = "S00001";
			if ("SZ".equalsIgnoreCase(city)) {
				result = "S00002";
			}
			if ("DG".equalsIgnoreCase(city)) {
				result = "S00003";
			}
			if ("JM".equalsIgnoreCase(city)) {
				result = "S00004";
			}
			if ("FS".equalsIgnoreCase(city)) {
				result = "S00005";
			}
		}
		if (!Tools.hasText(result)) {
			result = defaultOrgId;
		}
		return result;
	}

	public void getResult(ResultAction action) {
		final String guid = action.getGuid();
		VOPext vOpext = null;

		final VOLms vOLms = vOLmsDAO.selectByPrimaryKey(guid);
		if (vOLms == null) {
			action.addActionError("找不到该记录");
			return;
		}
		action.setvOLms(vOLms);

		try {
			VOPextKey key = new VOPextKey();
			key.setEX_TYPE("保险金");
			key.setPL_ID(vOLms.getPL_ID());
			try {
				key.setEX_VALUE(String.valueOf(vOLms.getLMS_INSU_AMOUT().intValue()));
			} catch (Exception e) {
				logger.warn("数字转化出错", e);
			}

			vOpext = vOPextDAO.selectByPrimaryKey(key);
			if (vOpext == null) {
				logger.warn("查找保险金出错, 找不到记录");
			}
			action.setvOpext(vOpext);
		} catch (Exception e) {
			logger.warn("查找保险金出错", e);
		}

		try {
			VOPextExample example = new VOPextExample();
			example.createCriteria().andEX_TYPEEqualTo("合同").andPL_IDEqualTo(vOLms.getPL_ID());
			List hetongList = vOPextDAO.selectByExample(example);
			if (hetongList == null || hetongList.isEmpty()) {
				logger.warn("查找合同出错, 找不到记录");
			}
			action.setHetongList(hetongList);
		} catch (Exception e) {
			logger.warn("查找合同出错", e);
		}

		final VOPlan vOPlan = vOPlanDAO.selectByPrimaryKey(vOLms.getPL_ID());
		if (vOPlan == null) {
			action.addActionError("找不到产品记录");
			return;
		}
		action.setvOPlan(vOPlan);
		action.setvOplan(vOPlan);
		action.setDmFlag("no");
		if (vOPlan != null && "DM渠道".equals(vOPlan.getPL_TYPE())) {
			action.setDmFlag("yes");
		}

		List<ExtValue> extValues = new ArrayList<ExtValue>();
		if (Tools.hasText(vOPlan.getPL_EXTNAME1()) && Tools.hasText(vOpext.getEX_EXTVALUE1())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME1());
			ev.setValue(vOpext.getEX_EXTVALUE1());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME2()) && Tools.hasText(vOpext.getEX_EXTVALUE2())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME2());
			ev.setValue(vOpext.getEX_EXTVALUE2());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME3()) && Tools.hasText(vOpext.getEX_EXTVALUE3())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME3());
			ev.setValue(vOpext.getEX_EXTVALUE3());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME4()) && Tools.hasText(vOpext.getEX_EXTVALUE4())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME4());
			ev.setValue(vOpext.getEX_EXTVALUE4());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME5()) && Tools.hasText(vOpext.getEX_EXTVALUE5())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME5());
			ev.setValue(vOpext.getEX_EXTVALUE5());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME6()) && Tools.hasText(vOpext.getEX_EXTVALUE6())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME6());
			ev.setValue(vOpext.getEX_EXTVALUE6());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME7()) && Tools.hasText(vOpext.getEX_EXTVALUE7())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME7());
			ev.setValue(vOpext.getEX_EXTVALUE7());
			extValues.add(ev);
		}
		if (Tools.hasText(vOPlan.getPL_EXTNAME8()) && Tools.hasText(vOpext.getEX_EXTVALUE8())) {
			ExtValue ev = new ExtValue();
			ev.setName(vOPlan.getPL_EXTNAME8());
			ev.setValue(vOpext.getEX_EXTVALUE8());
			extValues.add(ev);
		}
		if (extValues.size() > 0) {
			action.setExtValues(extValues);
		} else {
			action.setExtValues(null);
		}
	}

	public void preparePlans(HttpServletRequest request) {

		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("重疾保障");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			request.setAttribute("list1", list);
		}

		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("少儿教育");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			request.setAttribute("list2", list);
		}

		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("养老年金");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			request.setAttribute("list3", list);
		}
	}

	public VOFile getVOFile(String id) {
		return vOFileDAO.selectByPrimaryKey(id);
	}

	public ServiceResult sentLms(VOLms bean, boolean shouldCheckMobile) {
		ServiceResult result = new ServiceResult();
		try {

			final VOLms lookup = vOLmsDAO.selectByPrimaryKey(bean.getLMS_GUID());
			if (lookup == null) {
				result.setCode("03");
				result.setErrorMsg("找不到记录");
				return result;
			}

			boolean needSendLMS = false;
			if (shouldCheckMobile) {
				// Validate LMS START =============================
				VOLmsExample validateExample = new VOLmsExample();
				validateExample.createCriteria().andLMS_MOBILEEqualTo(lookup.getLMS_MOBILE()).andLMS_FLAG_VARIFYEqualTo("Y")
						.andLMS_SEND_FLAGEqualTo("Y");

				List validateList = vOLmsDAO.selectByExample(validateExample);
				if (validateList != null && validateList.size() > 0) {
					String code = "02";
					String msg = "该手机号已经发送过LMS了";
					result.setCode(code);
					result.setErrorMsg(msg);

					lookup.setLMS_SEND_FLAG("N");
					lookup.setLMS_SEND_REF(code);
					lookup.setLMS_SEND_WHY(msg);
					lookup.setLMS_SEND_DATE(Tools.getToday());
					lookup.setLMS_SEND_TIME(Tools.getTime());
					vOLmsDAO.updateByPrimaryKey(lookup);

					return result;
				} else {
					needSendLMS = true;
				}
			}// Validate LMS END =============================
			else {
				needSendLMS = true;
			}

			if (needSendLMS) { // 重要，发送LMS START =============================
				String tmplate = makeLmsTmplate(lookup);
				logger.debug("****************  PRINT LMS REQUEST START  ****************");
				logger.debug(tmplate);
				logger.debug("****************  PRINT LMS REQUEST END    ****************");

				if ("dev".equalsIgnoreCase(Tools.getProperties("website.evn"))) {
					String code = "01";
					String msg = "测试环境下跳过LMS接口";
					result.setCode(code);
					result.setErrorMsg(msg);

					lookup.setLMS_SEND_FLAG("N");
					lookup.setLMS_SEND_REF(code);
					lookup.setLMS_SEND_WHY(msg);
					lookup.setLMS_SEND_DATE(Tools.getToday());
					lookup.setLMS_SEND_TIME(Tools.getTime());
					vOLmsDAO.updateByPrimaryKey(lookup);

					return result;
				} else {
					try {
						// 开始发送
						logger.debug(">>>>>>>>>>> Send LMS start");
						HttpURLConnection connection = null;
						// String endpoint =
						// Tools.getProperties("host_lms.address");
						String endpoint = Tools.getDatabaseProperty("service", "address_lms");
						logger.debug("LMS endpoint=" + endpoint);

						long beforeTime = System.currentTimeMillis();
						connection = (HttpURLConnection) new URL(endpoint).openConnection();
						connection.setDoOutput(true);
						connection.setDoInput(true);
						connection.setRequestMethod("POST");
						connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
						connection.setRequestProperty("soapaction", "");
						connection.setConnectTimeout(5000);
						connection.setReadTimeout(5000);
						connection.connect();
						OutputStream os = connection.getOutputStream();
						os.write(tmplate.getBytes("UTF-8"));
						os.flush();
						os.close();
						InputStream is = connection.getInputStream();// 获取数据，真正的请求从此处开始
						byte[] bts = new byte[is.available()];
						is.read(bts);
						String returnString = new String(bts, "UTF-8");
						long afterTime = System.currentTimeMillis();
						logger.debug("LMS成功返回！耗时:" + (afterTime - beforeTime) + "ms");
						logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE START  %%%%%%%%%%%%%%%%");
						logger.debug(returnString);
						logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE END    %%%%%%%%%%%%%%%%");

						String code = "00";
						String msg = "成功";
						result.setCode(code);
						result.setErrorMsg(msg);

						lookup.setLMS_SEND_FLAG("Y");
						lookup.setLMS_SEND_REF(code);
						lookup.setLMS_SEND_WHY(msg);
						lookup.setLMS_SEND_DATE(Tools.getToday());
						lookup.setLMS_SEND_TIME(Tools.getTime());
						vOLmsDAO.updateByPrimaryKey(lookup);

						return result;
					} catch (Throwable e) {
						String msgLong = "LMS接口调用失败:" + e;
						logger.error(msgLong, e);

						String msgShort = msgLong;
						if (msgShort.length() > 50) {
							msgShort = msgShort.substring(0, 50) + "..";
						}

						String code = "99";
						String msg = msgShort;
						result.setCode(code);
						result.setErrorMsg(msg);

						lookup.setLMS_SEND_FLAG("N");
						lookup.setLMS_SEND_REF(code);
						lookup.setLMS_SEND_WHY(msg);
						lookup.setLMS_SEND_DATE(Tools.getToday());
						lookup.setLMS_SEND_TIME(Tools.getTime());
						vOLmsDAO.updateByPrimaryKey(lookup);

						return result;
					}
				}
			}// 重要，发送LMS END =============================

		} catch (Throwable e) {
			String msgLong = "发送LMS失败:" + e;
			logger.error(msgLong, e);
			String msgShort = msgLong;
			if (msgShort.length() > 50) {
				msgShort = msgShort.substring(0, 50) + "..";
			}

			String code = "99";
			String msg = msgShort;
			result.setCode(code);
			result.setErrorMsg(msg);

			try {
				bean.setLMS_SEND_FLAG("N");
				bean.setLMS_SEND_REF(code);
				bean.setLMS_SEND_WHY(msg);
				bean.setLMS_SEND_DATE(Tools.getToday());
				bean.setLMS_SEND_TIME(Tools.getTime());
				vOLmsDAO.updateByPrimaryKey(bean);
			} catch (Throwable e2) {
				logger.warn("忽略错误,找不到记录? :" + e2, e2);
			}

			return result;
		}

		if (result.getCode() == null) {
			result.setCode("99");
			result.setErrorMsg("未知错误");
			logger.warn("未知错误,不应执行到此处");
		}
		return result;
	}

	public VOLms fetchOneLms(String refid) {
		return vOLmsDAO.selectByPrimaryKey(refid);
	}

	public void PrmForm3Json(com.aia.prm.web.json.PrmForm3Json action) {
		final VOLms lms = action.getLms();
		final String mobile = lms.getLMS_MOBILE();
		VOLms lookup = null; // 初始记录
		VOLms clonedLookup = null; // 克隆初始记录，更改guid后再保存
		int mobileActCount = 0;
		boolean isFindName = false; // 从历史记录中寻找这个手机号，如果找到就标记为true
		VOLms find = null;

		{// 校验手机号 是非空的
			if (!Tools.hasText(mobile)) {
				action.addActionError("系统出错了，传入的手机号参数为空");
				return;
			}

		}

		{// 校验是否已经手机激活LMS记录了
			lookup = vOLmsDAO.selectByPrimaryKey(lms.getLMS_GUID());
			if (lookup == null) {
				action.addActionError("不存在该记录，请检查页面参数，并返回主页");
				return;
			}
			if (Constant.Y.equalsIgnoreCase(lookup.getLMS_FLAG_VARIFY())) {
				action.addActionError("您已提交过个人的信息，我们将会尽快安排营销员与您联系。请返回主页浏览其他产品，或填写其他手机号码！");
				return;
			}
			clonedLookup = (VOLms) Tools.doClone(lookup);
			if (clonedLookup == null) {
				action.addActionError("未知错误");
				logger.error("Tools.doClone出错");
				return;
			}
		}

		{// 查询过去的记录看用户是否已经提交过[姓名，城市等]信息，如果有，则将[姓名，城市等]信息更新上去

			VOLmsExample example = new VOLmsExample();
			example.createCriteria().andLMS_MOBILEEqualTo(mobile).andLMS_LX_NAMEIsNotNull();
			example.setOrderByClause("LMS_DATE desc, LMS_TIME desc");
			List list = vOLmsDAO.selectByExample(example);
			if (list != null && !list.isEmpty()) {
				isFindName = true;
				find = (VOLms) list.get(0); // Assert lookup not null!
			}
		}

		{// 更新lookup到数据库
			if (isFindName) {
				clonedLookup.setLMS_LX_PROVINCE(find.getLMS_LX_PROVINCE());
				clonedLookup.setLMS_LX_CITY(find.getLMS_LX_CITY());
				clonedLookup.setLMS_LX_DISTRICT(find.getLMS_LX_DISTRICT());
				clonedLookup.setLMS_LX_NAME(find.getLMS_LX_NAME());
				clonedLookup.setLMS_LX_AGE(find.getLMS_LX_AGE());
				clonedLookup.setLMS_LX_SEX(find.getLMS_LX_SEX());
			} else {
				// 极少数情况下，找不到之前的记录，那么视做游客，将重要字段用默认值补全。
				clonedLookup.setLMS_LX_PROVINCE("SH");
				clonedLookup.setLMS_LX_CITY("SH");
				clonedLookup.setLMS_LX_DISTRICT("上海");
				clonedLookup.setLMS_LX_NAME("游客");
				clonedLookup.setLMS_LX_AGE(30l);
				clonedLookup.setLMS_LX_SEX("M");
			}

			clonedLookup.setLMS_MOBILE(mobile);
			clonedLookup.setLMS_MOBILE_COUNT(6L);
			clonedLookup.setLMS_DATE(Tools.getToday());
			clonedLookup.setLMS_TIME(Tools.getTime());
			clonedLookup.setLMS_GUID(Tools.GUID());

			clonedLookup.setLMS_FREEFLAG3("Y");
			{// 标记状态04
				String code = "04";
				String msg = "发短信的次数达到上限";
				clonedLookup.setLMS_SEND_FLAG("N");
				clonedLookup.setLMS_SEND_REF(code);
				clonedLookup.setLMS_SEND_WHY(msg);
			}
			{// 保费信息初始化，还有其他重要字段的设值
				clonedLookup.setLMS_FISRT_AMOUT(BigDecimal.valueOf(0L));
				clonedLookup.setLMS_FLAG_VARIFY("N"); // 手机未通过校验
				clonedLookup.setLMS_VARIFY_CODE("000000"); // 手机未通过校验
			}
			vOLmsDAO.insert(clonedLookup);
			action.setNewid(clonedLookup.getLMS_GUID());
		}

	}

	public void saveFile(VOFile myImage) {
		vOFileDAO.insert(myImage);
	}

	@SuppressWarnings("rawtypes")
	public void updateQne(CorpAction action) {
		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}
		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QneExample example = new QneExample();
			example.createCriteria().andQNE_PHOEqualTo(mobile);
			List list = qneDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已领取国际SOS紧急救援服务，请勿重复领取，感谢您的参与！");
				return;
			}
		}

		Qne record = new Qne();
		record.setQNE_ADRESS(action.getAddress());
		record.setQNE_BASE(action.getBase());
		record.setQNE_BIRTH(action.getBirth());
		record.setQNE_NAME(action.getName());
		record.setQNE_VALIDATE(action.getValidate());
		record.setQNE_PHO(action.getPho());
		record.setQNE_SEX(action.getW_name());
		record.setQNE_GUID(Tools.GUID());
		record.setQNE_SEND_FLAG("N");
		record.setQNE_DATE(Tools.getToday());
		record.setQNE_TIME(Tools.getTime());
		qneDAO.insert(record);

		{// 插入SMSLOG表
			SmsLog smslog = new SmsLog();
			smslog.setSMSLOG_GUID(Tools.GUID());
			smslog.setSMSLOG_DATE(Tools.getToday());
			smslog.setSMSLOG_TIME(Tools.getTime());
			smslog.setSMSLOG_MOBILE(action.getPho());
			smslog.setSMSLOG_FREETEXT1("去哪儿:" + record.getQNE_GUID());
			smsLogDAO.insertSelective(smslog);
		}
		String msg = "您已成功获得由友邦保险提供的国际SOS紧急旅行医疗救援服务。有效期2013/1/1至2013/12/31。国际SOS热线电话: 4008180169(国内)，+864008180169或+8601064105566(国外)。";
		try {
			sendSMS(msg, mobile, "SOS", true);
			record.setQNE_SEND_FLAG("Y");
			qneDAO.updateByPrimaryKeySelective(record);
		} catch (Exception e) {
			logger.error("发短信失败", e);
		}
	}

	public void PrmResultJson(PrmResultJson action) {
		final String guid = action.getGuid();
		VOLms lookup = null;

		{// 校验非空
			if (!Tools.hasText(guid)) {
				action.addActionError("系统出错了，传入的参数为空");
				return;
			}
		}

		{// 校验是否已经手机激活LMS记录了
			lookup = vOLmsDAO.selectByPrimaryKey(guid);
			if (lookup == null) {
				action.addActionError("不存在该记录，请检查页面参数");
				return;
			}
			if (Constant.Y.equalsIgnoreCase(lookup.getLMS_FREEFLAG3())) {
				action.addActionError("您之前已经提交过个人的信息，我们将会尽快安排营销员与您联系。");
				return;
			}
		}

		{// 更新lookup到数据库
			lookup.setLMS_FREEFLAG3("Y");
			vOLmsDAO.updateByPrimaryKey(lookup);
		}

		ServiceResult result = sentLms(lookup, true);
		if (logger.isDebugEnabled()) {
			if (result != null && !"00".equals(result.getCode())) {
				logger.warn("前端用户发送LMS没有成功!");
			}
		}
	}

	private static Map<String, String> advisers = new HashMap<String, String>();
	static {
		/*
		 * 友邦小马哥, 心安是福 快乐无价, 四眼唐兄, 喜洋洋, 保无忧
		 */
		advisers.put("友邦小马哥", "1");
		advisers.put("心安是福 快乐无价", "2");
		advisers.put("四眼唐兄", "3");
		advisers.put("喜洋洋", "4");
		advisers.put("保无忧", "5");
	}

	@SuppressWarnings("rawtypes")
	public void updateQneAx(CorpAxAction action) {
		final String adviser = action.getAdviser();

		if (!Tools.hasText(adviser)) {
			action.addActionError("营销员参数为空");
			return;
		}
		if (!advisers.containsKey(adviser)) {
			action.addActionError("你选择的营销员[" + adviser + "]不存在");
			return;
		}

		final String adviserCode = advisers.get(adviser);

		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}
		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QnbeExample example = new QnbeExample();
			example.createCriteria().andQNXE_PHOEqualTo(mobile);
			List list = qnbeDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已参与过活动，请勿重复提交，感谢您的参与！");
				return;
			}
		}

		Qnbe record = new Qnbe();
		record.setQNXE_ADRESS(action.getAddress());
		record.setQNXE_BASE(action.getBase());
		record.setQNXE_BIRTH(action.getBirth());
		record.setQNXE_NAME(action.getName());
		record.setQNXE_VALIDATE(action.getValidate());
		record.setQNXE_PHO(action.getPho());
		record.setQNXE_SEX(action.getW_name());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());
		record.setQNXE_AGENTTYPE(adviser);
		record.setQNXE_CODE(adviserCode);
		qnbeDAO.insert(record);

		String msg = "您已成功参与友邦保险“Top营销员就在我身边”，在3个工作日内，将会安排您所选择的营销员与您取得联系，请保持手机畅通，" + "同时您还可以参与幸运大抽奖。友邦在线投保了解更多ebiz.aia.com.cn";
		sendSMS(msg, mobile, "安欣:" + record.getQNXE_GUID(), false);

		ServiceResult result = sendAxLms(record);

	}

	public ServiceResult sendAxLms(Qnbe lookup) {
		ServiceResult result = new ServiceResult();
		try {
			String tmplate = makeAxLmsTmplate(lookup);
			logger.debug("****************  PRINT LMS REQUEST START  ****************");
			logger.debug(tmplate);
			logger.debug("****************  PRINT LMS REQUEST END    ****************");

			if ("dev".equalsIgnoreCase(Tools.getProperties("website.evn"))) {
				String code = "01";
				String msg = "测试环境下跳过LMS接口";
				result.setCode(code);
				result.setErrorMsg(msg);
				lookup.setQNXE_UNICA_FLAG("N");
				lookup.setQNXE_UNICA_CODE(code);
				lookup.setQNXE_UNICA_REMARK(msg);
				qnbeDAO.updateByPrimaryKey(lookup);
				return result;
			} else {

				// 开始发送
				logger.debug(">>>>>>>>>>> Send LMS start");
				HttpURLConnection connection = null;
				String endpoint = Tools.getDatabaseProperty("service", "address_lms");
				logger.debug("LMS endpoint=" + endpoint);
				long beforeTime = System.currentTimeMillis();
				connection = (HttpURLConnection) new URL(endpoint).openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
				connection.setRequestProperty("soapaction", "");
				connection.setConnectTimeout(5000);
				connection.setReadTimeout(5000);
				connection.connect();
				OutputStream os = connection.getOutputStream();
				os.write(tmplate.getBytes("UTF-8"));
				os.flush();
				os.close();
				InputStream is = connection.getInputStream();// 获取数据，真正的请求从此处开始
				byte[] bts = new byte[is.available()];
				is.read(bts);
				String returnString = new String(bts, "UTF-8");
				long afterTime = System.currentTimeMillis();
				logger.debug("LMS成功返回！耗时:" + (afterTime - beforeTime) + "ms");
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE START  %%%%%%%%%%%%%%%%");
				logger.debug(returnString);
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE END    %%%%%%%%%%%%%%%%");

				String code = "00";
				String msg = "成功";
				result.setCode(code);
				result.setErrorMsg(msg);

				lookup.setQNXE_UNICA_FLAG("Y");
				lookup.setQNXE_UNICA_CODE(code);
				lookup.setQNXE_UNICA_REMARK(msg);
				if (returnString.length() > 1500) {
					returnString = returnString.substring(0, 1500);
				}
				lookup.setQNXE_UNICA_RESPONSE(returnString);

				qnbeDAO.updateByPrimaryKey(lookup);
				return result;
			}
		} catch (Throwable e) {
			String msgLong = "LMS接口调用失败:" + e;
			logger.error(msgLong, e);
			String msgShort = msgLong;
			if (msgShort.length() > 50) {
				msgShort = msgShort.substring(0, 50) + "..";
			}
			String code = "99";
			String msg = msgShort;
			result.setCode(code);
			result.setErrorMsg(msg);
			lookup.setQNXE_UNICA_FLAG("N");
			lookup.setQNXE_UNICA_CODE(code);
			lookup.setQNXE_UNICA_REMARK(msg);
			qnbeDAO.updateByPrimaryKey(lookup);
			return result;
		}
	}

	public ServiceResult sendAysLms(Qnde lookup) {
		ServiceResult result = new ServiceResult();
		try {
			String tmplate = makeAysLmsTmplate(lookup);
			logger.debug("****************  PRINT LMS REQUEST START  ****************");
			logger.debug(tmplate);
			logger.debug("****************  PRINT LMS REQUEST END    ****************");

			if ("dev".equalsIgnoreCase(Tools.getProperties("website.evn"))) {
				String code = "01";
				String msg = "测试环境下跳过LMS接口";
				result.setCode(code);
				result.setErrorMsg(msg);
				lookup.setQNXE_UNICA_FLAG("N");
				lookup.setQNXE_UNICA_CODE(code);
				lookup.setQNXE_UNICA_REMARK(msg);
				qndeDAO.updateByPrimaryKey(lookup);
				return result;
			} else {

				// 开始发送
				logger.debug(">>>>>>>>>>> Send LMS start");
				HttpURLConnection connection = null;
				String endpoint = Tools.getDatabaseProperty("service", "address_lms");
				logger.debug("LMS endpoint=" + endpoint);
				long beforeTime = System.currentTimeMillis();
				connection = (HttpURLConnection) new URL(endpoint).openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
				connection.setRequestProperty("soapaction", "");
				connection.setConnectTimeout(5000);
				connection.setReadTimeout(5000);
				connection.connect();
				OutputStream os = connection.getOutputStream();
				os.write(tmplate.getBytes("UTF-8"));
				os.flush();
				os.close();
				InputStream is = connection.getInputStream();// 获取数据，真正的请求从此处开始
				byte[] bts = new byte[is.available()];
				is.read(bts);
				String returnString = new String(bts, "UTF-8");
				long afterTime = System.currentTimeMillis();
				logger.debug("LMS成功返回！耗时:" + (afterTime - beforeTime) + "ms");
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE START  %%%%%%%%%%%%%%%%");
				logger.debug(returnString);
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE END    %%%%%%%%%%%%%%%%");

				String code = "00";
				String msg = "成功";
				result.setCode(code);
				result.setErrorMsg(msg);

				lookup.setQNXE_UNICA_FLAG("Y");
				lookup.setQNXE_UNICA_CODE(code);
				lookup.setQNXE_UNICA_REMARK(msg);
				if (returnString.length() > 1500) {
					returnString = returnString.substring(0, 1500);
				}
				lookup.setQNXE_UNICA_RESPONSE(returnString);

				qndeDAO.updateByPrimaryKey(lookup);
				return result;
			}
		} catch (Throwable e) {
			String msgLong = "LMS接口调用失败:" + e;
			logger.error(msgLong, e);
			String msgShort = msgLong;
			if (msgShort.length() > 50) {
				msgShort = msgShort.substring(0, 50) + "..";
			}
			String code = "99";
			String msg = msgShort;
			result.setCode(code);
			result.setErrorMsg(msg);
			lookup.setQNXE_UNICA_FLAG("N");
			lookup.setQNXE_UNICA_CODE(code);
			lookup.setQNXE_UNICA_REMARK(msg);
			qndeDAO.updateByPrimaryKey(lookup);
			return result;
		}
	}

	public ServiceResult sendTypaLms(Qnae lookup) {
		ServiceResult result = new ServiceResult();
		try {
			String tmplate = makeTypaLmsTmplate(lookup);
			logger.debug("****************  PRINT LMS REQUEST START  ****************");
			logger.debug(tmplate);
			logger.debug("****************  PRINT LMS REQUEST END    ****************");
			if ("dev".equalsIgnoreCase(Tools.getProperties("website.evn"))) {
				String code = "01";
				String msg = "测试环境下跳过LMS接口";
				result.setCode(code);
				result.setErrorMsg(msg);
				lookup.setQNXE_UNICA_FLAG("N");
				lookup.setQNXE_UNICA_CODE(code);
				lookup.setQNXE_UNICA_REMARK(msg);
				qnaeDAO.updateByPrimaryKey(lookup);
				return result;
			} else {
				// 开始发送
				logger.debug(">>>>>>>>>>> Send LMS start");
				HttpURLConnection connection = null;
				String endpoint = Tools.getDatabaseProperty("service", "address_lms");
				logger.debug("LMS endpoint=" + endpoint);
				long beforeTime = System.currentTimeMillis();
				connection = (HttpURLConnection) new URL(endpoint).openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
				connection.setRequestProperty("soapaction", "");
				connection.setConnectTimeout(5000);
				connection.setReadTimeout(5000);
				connection.connect();
				OutputStream os = connection.getOutputStream();
				os.write(tmplate.getBytes("UTF-8"));
				os.flush();
				os.close();
				InputStream is = connection.getInputStream();// 获取数据，真正的请求从此处开始
				byte[] bts = new byte[is.available()];
				is.read(bts);
				String returnString = new String(bts, "UTF-8");
				long afterTime = System.currentTimeMillis();
				logger.debug("LMS成功返回！耗时:" + (afterTime - beforeTime) + "ms");
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE START  %%%%%%%%%%%%%%%%");
				logger.debug(returnString);
				logger.debug("%%%%%%%%%%%%%%%%  PRINT LMS RESPONSE END    %%%%%%%%%%%%%%%%");

				String code = "00";
				String msg = "成功";
				result.setCode(code);
				result.setErrorMsg(msg);

				lookup.setQNXE_UNICA_FLAG("Y");
				lookup.setQNXE_UNICA_CODE(code);
				lookup.setQNXE_UNICA_REMARK(msg);
				if (returnString.length() > 1500) {
					returnString = returnString.substring(0, 1500);
				}
				lookup.setQNXE_UNICA_RESPONSE(returnString);

				qnaeDAO.updateByPrimaryKey(lookup);
				return result;
			}
		} catch (Throwable e) {
			String msgLong = "LMS接口调用失败:" + e;
			logger.error(msgLong, e);
			String msgShort = msgLong;
			if (msgShort.length() > 50) {
				msgShort = msgShort.substring(0, 50) + "..";
			}
			String code = "99";
			String msg = msgShort;
			result.setCode(code);
			result.setErrorMsg(msg);
			lookup.setQNXE_UNICA_FLAG("N");
			lookup.setQNXE_UNICA_CODE(code);
			lookup.setQNXE_UNICA_REMARK(msg);
			qnaeDAO.updateByPrimaryKey(lookup);
			return result;
		}
	}

	private int sendSMS(String msg, String mobile, String remark, boolean isThrowException) {
		try {
			{// 插入SMSLOG表
				SmsLog smslog = new SmsLog();
				smslog.setSMSLOG_GUID(Tools.GUID());
				smslog.setSMSLOG_DATE(Tools.getToday());
				smslog.setSMSLOG_TIME(Tools.getTime());
				smslog.setSMSLOG_MOBILE(mobile);
				smslog.setSMSLOG_FREETEXT1(remark);
				smsLogDAO.insertSelective(smslog);
			}

			if (logger.isDebugEnabled()) {
				logger.debug("Print SMS>" + msg);
			}

			String sql = "INSERT INTO TT_AIA_SMS_MT (EXTEND_TYPE, SP_SERVICE_CODE, PRIORITY, PARAM_ONE, PARAM_TWO, DESTINATION_ADDR, CONTENT) VALUES (- 1, '03', 9, '0986', 'T04W02', ?, ?)";
			return jdbcTemplate.update(sql, new Object[] { mobile, msg });
		} catch (RuntimeException e) {
			logger.error("发短信失败", e);
			if (isThrowException) {
				throw e;
			} else {
				return 0;
			}
		}

	}

	@SuppressWarnings("rawtypes")
	public void updateQneTypa(CorpTypaAction action) {
		ChinaAddress add = null;
		try {
			add = CompanyCodes.translateToAddress(action.getAddress());
		} catch (AddressNotFoundException e) {
			logger.error("传入的省市参数错误", e);
			action.addActionError("传入的省市参数错误");
			return;
		}

		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}
		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QnaeExample example = new QnaeExample();
			example.createCriteria().andQNXE_PHOEqualTo(mobile);
			List list = qnaeDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已领取国际SOS紧急救援服务，请勿重复领取，感谢您的参与！");
				return;
			}
		}
		Card card = null;
		{// 得到卡号密码
			CardExample cardExample = new CardExample();
			cardExample.createCriteria().andCARD_USED_FLAGIsNull().andCARD_FREETEXT1EqualTo(add.getProviceName());
			cardExample.or(cardExample.createCriteria().andCARD_USED_FLAGNotEqualTo("Y").andCARD_FREETEXT1EqualTo(add.getProviceName()));
			cardExample.setOrderByClause("CARD_ID");

			try {// 卡数少于200报警
				int cardNumber = cardDAO.mm_countByExample(cardExample);
				logger.debug(add.getProviceName() + "分公司的当前卡片数量:" + cardNumber);
				if (cardNumber <= 200) {
					String msg = add.getProviceName() + "分公司的TYPA卡的张数为" + cardNumber + "，请尽快补足";
					String alertMobiles = Tools.getProperties("alertsms");
					String[] array = alertMobiles.split(",");
					for (String alertMobile : array) {
						sendSMS(msg, alertMobile, "ALERT", false);
					}
				}
			} catch (Exception e) {
				logger.error("不能发送卡片数量预警", e);
			}

			List cardList = cardDAO.selectByExample(cardExample, 0, 1);
			if (cardList != null && cardList.size() > 0) {
				card = (Card) cardList.get(0);

			} else {
				logger.error("没有可用的激活卡!");
			}
		}

		Qnae record = new Qnae();
		record.setQNXE_ADRESS(action.getAddress());
		record.setQNXE_BASE(action.getBase());
		record.setQNXE_BIRTH(action.getBirth());
		record.setQNXE_NAME(action.getName());
		record.setQNXE_VALIDATE(action.getValidate());
		record.setQNXE_PHO(action.getPho());
		record.setQNXE_SEX(action.getW_name());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());

		record.setQNXE_FREETEXT3(add.getCompanyCode());
		record.setQNXE_FREETEXT4(add.getProviceName());
		record.setQNXE_PROVINCE(add.getProvinceCode());
		record.setQNXE_CITY(add.getCityCode());
		record.setQNXE_DISTRICT(add.getDistCode());

		String cardNo = "";
		String cardPwd = "";
		if (card != null) {
			cardNo = card.getCARD_NO();
			cardPwd = card.getCARD_PWD();
			// 更新卡表
			card.setCARD_USED_FLAG("Y");
			card.setCARD_BYWHO(record.getQNXE_NAME());
			card.setCARD_PHONE(record.getQNXE_PHO());
			card.setCARD_DATE(Tools.getToday());
			card.setCARD_TIME(Tools.getTime());
			cardDAO.updateByPrimaryKey(card);
		} else {
			cardNo = "空";
			cardPwd = "空";
		}

		record.setQNXE_FREETEXT1(cardNo);
		record.setQNXE_FREETEXT2(cardPwd);
		record.setQNXE_FROM(action.getFrom());
		qnaeDAO.insert(record);

		{// 发激活短信
			String msg = "您已获赠《友邦畅游保意外伤害保险》激活卡。您的卡号是：" + cardNo + "，密码是：" + cardPwd
					+ "。请在2014年1月31日前登陆ebiz.aia.com.cn，选择“卡片激活”并根据页面提示完成激活，过期无效。如有疑问，请拨打友邦保险客服热线800-820-3588";
			sendSMS(msg, mobile, "TYPA-CARD:" + record.getQNXE_GUID(), false);
		}

		{// 发第二条短信
			String msg = "您已成功获得国际SOS紧急救援服务。服务由次月1日起生效，有效期12个月。国际SOS紧急救援热线电话: 4008-180-169(国内)，+86-4008-180-169或+86-010-6410-5566(国外)。";
			sendSMS(msg, mobile, "TYPA-SOS:" + record.getQNXE_GUID(), false);
		}

		ServiceResult result = sendTypaLms(record);
	}

	public void updateCoupon(CorpCouponAction action) {
		ChinaAddress add = null;
		try {
			add = CompanyCodes.translateToAddress(action.getAddress());
		} catch (AddressNotFoundException e) {
			logger.error("传入的省市参数错误", e);
			action.addActionError("传入的省市参数错误");
			return;
		}

		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}
		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QnceExample example = new QnceExample();
			example.createCriteria().andQNXE_PHOEqualTo(mobile);
			List list = qnceDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已领取过，请勿重复领取，感谢您的参与！");
				return;
			}
		}
		Coupon card = null;
		{// 得到卡号密码
			CouponExample cardExample = new CouponExample();
			cardExample.createCriteria().andCARD_USED_FLAGIsNull();
			cardExample.or(cardExample.createCriteria().andCARD_USED_FLAGNotEqualTo("Y"));
			cardExample.setOrderByClause("CARD_ID");

			List cardList = couponDAO.selectByExample(cardExample, 0, 1);
			if (cardList != null && cardList.size() > 0) {
				card = (Coupon) cardList.get(0);
			} else {
				logger.error("没有可用的优惠券!");
				try {
					// 短信通知
					String msg = "[minisite/ays-coupon]爱婴室优惠券已经用完，请尽快补足";
					String alertMobiles = Tools.getProperties("alertsms");
					String[] array = alertMobiles.split(",");
					for (String alertMobile : array) {
						sendSMS(msg, alertMobile, "ALERT", false);
					}
				} catch (Exception e) {
					logger.error("优惠券不足的短信通知失败", e);
				}
			}
		}

		Qnce record = new Qnce();
		record.setQNXE_ADRESS(action.getAddress());
		record.setQNXE_BASE(action.getBase());
		record.setQNXE_BIRTH(action.getBirth());
		record.setQNXE_NAME(action.getName());
		record.setQNXE_VALIDATE(action.getValidate());
		record.setQNXE_PHO(action.getPho());
		record.setQNXE_SEX(action.getW_name());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());

		record.setQNXE_FREETEXT3(add.getCompanyCode());
		record.setQNXE_FREETEXT4(add.getProviceName());
		record.setQNXE_PROVINCE(add.getProvinceCode());
		record.setQNXE_CITY(add.getCityCode());
		record.setQNXE_DISTRICT(add.getDistCode());

		String cardNo = "";
		String cardPwd = "";
		if (card != null) {
			cardNo = card.getCARD_NO();
			cardPwd = card.getCARD_PWD();
			// 更新卡表
			card.setCARD_USED_FLAG("Y");
			card.setCARD_BYWHO(record.getQNXE_NAME());
			card.setCARD_PHONE(record.getQNXE_PHO());
			card.setCARD_DATE(Tools.getToday());
			card.setCARD_TIME(Tools.getTime());
			couponDAO.updateByPrimaryKey(card);
		} else {
			cardNo = "空";
			cardPwd = "空";
		}

		record.setQNXE_FREETEXT1(cardNo);
		record.setQNXE_FREETEXT2(cardPwd);
		qnceDAO.insert(record);

		{// 发激活短信
			String msg = "您已获赠爱婴室5元抵扣券，使用密码" + cardNo + "，您可在2013年6月20日前至爱婴室各门店使用，每人限抵一次转发无效。如有疑问，请询爱婴室热线962513";
			sendSMS(msg, mobile, "AYS-CP:" + record.getQNXE_GUID(), false);
		}

	}

	public void updateQneAys(CorpAysAction action) {
		final String adviser = action.getAdviser();

		if (!Tools.hasText(adviser)) {
			action.addActionError("营销员参数为空");
			return;
		}
		if (!advisers.containsKey(adviser)) {
			action.addActionError("你选择的营销员[" + adviser + "]不存在");
			return;
		}

		final String adviserCode = advisers.get(adviser);

		if (!Tools.hasText(action.getPho())) {
			action.addActionError("手机号为空");
			return;
		}
		final String mobile = action.getPho().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QndeExample example = new QndeExample();
			example.createCriteria().andQNXE_PHOEqualTo(mobile);
			List list = qndeDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("您已参与过活动，请勿重复提交，感谢您的参与！");
				return;
			}
		}

		Qnde record = new Qnde();
		record.setQNXE_ADRESS(action.getAddress());
		record.setQNXE_BASE(action.getBase());
		record.setQNXE_BIRTH(action.getBirth());
		record.setQNXE_NAME(action.getName());
		record.setQNXE_VALIDATE(action.getValidate());
		record.setQNXE_PHO(action.getPho());
		record.setQNXE_SEX(action.getW_name());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());
		record.setQNXE_AGENTTYPE(adviser);
		record.setQNXE_CODE(adviserCode);
		qndeDAO.insert(record);

		// 不发短信
		// String msg =
		// "您已成功参与友邦保险“Top营销员就在我身边”，在3个工作日内，将会安排您所选择的营销员与您取得联系，请保持手机畅通，" +
		// "同时您还可以参与幸运大抽奖。友邦在线投保了解更多ebiz.aia.com.cn";
		// sendSMS(msg, mobile, "安欣:" + record.getQNXE_GUID());

		ServiceResult result = sendAysLms(record);

	}

	public void H7n9Form(H7n9Form action) {
		Qnfe record = action.getQnfe();
		if (!Tools.hasText(record.getQNXE_PHO())) {
			action.addActionError("手机号为空");
			return;
		}

		if (!StringUtils.isNumeric(record.getQNXE_BIRTH())) {
			action.addActionError("年龄格式不正格，请输入数字");
			return;
		}

		final String mobile = record.getQNXE_PHO().trim();
		if (mobile.length() != 11) {
			action.addActionError("手机号不为11位");
			return;
		}

		{// 每个手机号只能登记一次
			QnfeExample example = new QnfeExample();
			example.createCriteria().andQNXE_PHOEqualTo(mobile);

			List list = qnfeDAO.selectByExample(example);
			if (list != null && list.size() > 0) {
				action.addActionError("该手机号已经登记过，请勿重复提交，感谢您的参与！");
				return;
			}
		}
		String base = record.getQNXE_BASE();
		if (Tools.hasText(base)) {
			base = base.replaceAll("\\r|\\n", " ");
			if (base.length() > 50) {
				action.addActionError("您输入的保险需求内容过长");
				return;
			}
			record.setQNXE_BASE(base);
		}
		record.setQNXE_ADRESS(Tools.makeIPAddress());
		record.setQNXE_GUID(Tools.GUID());
		record.setQNXE_DATE(Tools.getToday());
		record.setQNXE_TIME(Tools.getTime());
		record.setQNXE_VALIDATE(action.getValidate());
		qnfeDAO.insert(record);
		removeCaptcha();
	}

	private void removeCaptcha() {
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			if (session != null) {
				session.setAttribute(Constant.CAPTCHA_SESSION_HOLDER, "");
			}
		} catch (Exception e) {
			logger.warn("removeCaptcha:" + e, e);
		}
	}

	public void PrmZanJson(PrmZanJson action) {
		final String id = action.getId();
		final String sessionKey = Tools.getToday() + "#" + id;
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			if (session != null) {
				String sessionValue = (String) session.getAttribute(sessionKey);
				if (sessionValue != null && "YES".equals(sessionValue)) {
					action.addActionError("今天已经赞过了");
					return;
				}
			}
		} catch (Exception e) {
			logger.warn("PrmZanJson get session:" + e, e);
		}

		VOPlan plan = vOPlanDAO.selectByPrimaryKey(id);
		if (plan == null) {
			action.addActionError("找不到产品");
			return;
		}

		Long count = plan.getPL_FREENUM1();
		if (count == null) {
			count = 0L;
		}
		count++;
		VOPlan newPlan = new VOPlan();
		newPlan.setPL_ID(id);
		newPlan.setPL_FREENUM1(count);
		vOPlanDAO.updateByPrimaryKeySelective(newPlan);

		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			if (session != null) {
				session.setAttribute(sessionKey, "YES");
			}
		} catch (Exception e) {
			logger.warn("PrmZanJson put session:" + e, e);
		}
	}

	public void preparePlans2(HttpServletRequest request) {
		{
			VOPlanExample example = new VOPlanExample();
			example.createCriteria().andPL_TYPEEqualTo("DM渠道");
			example.setOrderByClause("PL_ORDER");
			List list = vOPlanDAO.selectByExample(example);
			request.setAttribute("list1", list);
		}
	}

	public void resendLms() {
		try {
			MemoryLog.debug("自动重发任务启动");
			VOLmsExample example = new VOLmsExample();
			String threeDay = Tools.getTodayDiff(-3);
			// andLMS_FREEFLAG3EqualTo("Y")： 要求营销员联系的记录
			// andLMS_SEND_FLAGEqualTo("N")： 发送失败的记录
			example.createCriteria().andLMS_DATEGreaterThan(threeDay).andLMS_FREEFLAG3EqualTo("Y").andLMS_SEND_FLAGEqualTo("N");
			example.setOrderByClause("LMS_DATE desc, LMS_TIME desc");
			List list = vOLmsDAO.selectByExample(example);
			int size = 0;
			if (list == null || list.size() == 0) {
				MemoryLog.debug("找不到需要重发的记录");
			} else {
				size = list.size();
				MemoryLog.debug("重发记录数量为" + size);
			}
			for (int i = 0; i < size; i++) {
				if (i > 100) {
					MemoryLog.debug("数量超过100条，退出");
					break;
				}
				VOLms lms = (VOLms) list.get(i);
				Assert.notNull(lms, "LMS记录为空");
				MemoryLog.debug("重发第" + (i + 1) + "条记录, 手机号:" + lms.getLMS_MOBILE());
				ServiceResult result = sentLms(lms, false);
				if (result != null && !("00".equals(result.getCode()))) {
					MemoryLog.debug("重发第" + (i + 1) + "条记录失败, code=" + result.getCode() + ", msg=" + result.getErrorMsg());
				}
			}
			MemoryLog.debug("自动重发任务结束");
		} catch (Exception e) {
			MemoryLog.debug("自动重发任务出错:" + e);
			logger.error("自动重发LMS失败", e);
		}
	}
}
